package cn.net.yugu.doraemon.common.dal.entity;

import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.StringUtils;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

@Setter
@Getter
@Builder
public class LogBaseEntity {
    private String bizCode;
    private String bizId;
    private String agentId;
    private String customerId;
    private String message;
    private String exceptionMsg;
    private Map<String,Object> extraColumn;

    public static class LogBaseEntityBuilder {
        public LogBaseEntityBuilder putExtraColumn(String key, Object value) {
            if (StringUtils.isBlank(key) || Objects.isNull(value)){
                return this;
            }
            if (Objects.isNull(this.extraColumn)){
                this.extraColumn = new ConcurrentHashMap<>();
            }
            this.extraColumn.put(key, value);
            return this;
        }

        public String build() {
            return new LogBaseEntity(bizCode,bizId,agentId,customerId,message,exceptionMsg,extraColumn).toString();
        }
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        // 输出基本属性
        if (StringUtils.isNotBlank(bizCode)) {
            sb.append("bizCode=").append(bizCode).append(", ");
        }
        if (StringUtils.isNotBlank(bizId)) {
            sb.append("bizId=").append(bizId).append(", ");
        }
        if (StringUtils.isNotBlank(agentId)) {
            sb.append("agentId=").append(agentId).append(", ");
        }
        if (StringUtils.isNotBlank(customerId)) {
            sb.append("customerId=").append(customerId).append(", ");
        }
        if (StringUtils.isNotBlank(message)) {
            sb.append("message=").append(message).append(", ");
        }
        if (StringUtils.isNotBlank(exceptionMsg)){
            sb.append("exceptionMsg=").append(exceptionMsg).append(", ");
        }
        // 输出extraColumn中的键值对
        if (extraColumn != null && !extraColumn.isEmpty()) {
            for (Map.Entry<String, Object> entry : extraColumn.entrySet()) {
                if (Objects.nonNull(entry.getValue())) {
                    sb.append(entry.getKey()).append("=").append(entry.getValue()).append(", ");
                }
            }
        }
        // 删除最后一个逗号
        if (sb.length()>2) {
            sb.setLength(sb.length() - 2);
        }
        return sb.toString();
    }
}
